package com.cheng.student.controller.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet(name = "CheckCode", value = "/checkCode")
public class CheckCodeServlet
        extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        BufferedImage bufferedImage = new BufferedImage(100,40,BufferedImage.TYPE_INT_ARGB);//生成图片对象
        Graphics graphics = bufferedImage.getGraphics();//获取图片对象的画图器
        Random random = new Random(System.currentTimeMillis());//获取随机数对象
        String verificationCode = "";
        for (int i = 1;i <= 6;i++)//生成随机数
        {
            Integer code = random.nextInt(10);
            verificationCode += code.toString();
        }
        HttpSession session = request.getSession();
        session.setAttribute("verificationCode",verificationCode);//把验证码储存在session里
        session.setMaxInactiveInterval(30);//session存活30秒

        Font font = new Font("111",Font.PLAIN,20);
        graphics.setFont(font);//设置大小
        graphics.setColor(Color.BLACK);//设置颜色

        int x = random.nextInt(11);
        int y = random.nextInt(21);
        graphics.drawString(verificationCode,10 + x,13 + y);//往图片上写字

        graphics.setColor(Color.BLUE);//设置为蓝色
        for(int i = 0;i < 20;i++)//随机画20条线
        {
            graphics.drawLine(random.nextInt(100),random.nextInt(40),
                    random.nextInt(100),random.nextInt(40));
        }
        response.setContentType("image/png");
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(bufferedImage, "PNG", outputStream);//发送给网页

    }
}
